<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryRef" :inline="true" label-width="80px" style="margin-bottom: 16px;">
     
      <!-- <el-form-item label="身份" prop="identity">
        <el-input style="width: 240px" v-model="queryParams.identity" placeholder="请输入身份" clearable />
      </el-form-item> -->
      <el-form-item label="手机号" prop="phone">
        <el-input style="width: 240px" v-model="queryParams.phone" placeholder="请输入手机号" clearable />
      </el-form-item>
      <el-form-item label="姓名" prop="name">
        <el-input style="width: 240px" v-model="queryParams.name" placeholder="请输入姓名" clearable />
      </el-form-item>
      <el-form-item label="审核日期" prop="auditDate">
        <el-date-picker 
          v-model="queryParams.auditDate" 
          type="datetimerange" 
          range-separator="-" 
          start-placeholder="开始日期时间" 
          end-placeholder="结束日期时间" 
          style="width: 240px" 
        />
      </el-form-item>
      <el-form-item label="创建日期" prop="createdDate">
        <el-date-picker 
          v-model="queryParams.createdDate" 
          type="datetimerange" 
          range-separator="-" 
          start-placeholder="开始日期时间" 
          end-placeholder="结束日期时间" 
          style="width: 240px" 
        />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
        <el-button icon="Refresh" @click="resetQuery">重置</el-button>
        <!-- <el-button type="primary" icon="Plus" @click="drawerVisible = true">新增</el-button> -->
      </el-form-item>
    </el-form>
    <el-table :data="bindingList" v-loading="loading" border style="width: 100%">
      <el-table-column label="房屋" 
      prop="houseRoomId" min-width="200" >
      <template  #default="scope">
        <span>{{ scope.row.pmsHouseDto?.pmsHouse?.areaInfo }}{{scope.row.pmsHouseDto?.pmsHouse?.areaInfo?"#":""}} {{scope.row.pmsHouseDto?.pmsHouse?.roomCode }}</span>
      </template>
      </el-table-column>
      <el-table-column label="住户姓名" prop="liveUserId" min-width="120" >
        <template #default="scope">
          <span>{{ scope.row.pmsHouseBindAplly.name }}</span>
        </template>
      </el-table-column>
      <el-table-column label="身份" prop="identity" min-width="120" >
        <template #default="scope">
          <span>{{ scope.row.pmsHouseBindAplly.identity }}</span>
        </template>
      </el-table-column>
      <el-table-column label="手机号" prop="phone" min-width="120" >
        <template #default="scope">
          <span>{{ scope.row.pmsHouseBindAplly.phone }}</span>
        </template>
      </el-table-column>
      <!-- <el-table-column label="姓名" prop="name" min-width="120" >
        <template #default="scope">
            <span>{{ scope.row.pmsHouseBindAplly.phone }}</span>
        </template>
      </el-table-column> -->
      <el-table-column label="产权证明" min-width="120">
        <template #default="scope">
          <div v-if="scope.row.pmsHouseBindAplly.images && scope.row.pmsHouseBindAplly.images.length > 0" style="display: flex; align-items: center; gap: 8px;">
            <el-image 
              :src="scope.row.pmsHouseBindAplly.images[scope.row.currentImageIndex || 0]" 
              style="width: 60px; height: 60px; border-radius: 4px; cursor: pointer;"
              fit="cover"
              @click="handleImageClick(scope.row)"
              :preview-src-list="scope.row.pmsHouseBindAplly.images"
              :initial-index="scope.row.currentImageIndex || 0"
              :preview-teleported="true"
              :z-index="9999"
            />
           
            <span v-if="scope.row.pmsHouseBindAplly.images.length > 1" style="font-size: 12px; color: #666;">
              {{ (scope.row.currentImageIndex || 0) + 1 }}/{{ scope.row.pmsHouseBindAplly.images.length }}
            </span>
          </div>
          <span v-else style="color: #999;">暂无图片</span>
        </template>
      </el-table-column>
      <el-table-column label="审核状态" prop="auditStatus" min-width="120">
        <template #default="scope">
          <el-tag :type="auditStatusOptions.find(item => item.value == scope.row.pmsHouseBindAplly.auditStatus)?.type">
            {{ auditStatusOptions.find(item => item.value == scope.row.pmsHouseBindAplly.auditStatus)?.label }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column label="审核日期" prop="auditDate" min-width="180">
        <template #default="scope">
          <span>{{ scope.row.pmsHouseBindAplly.auditDate }}</span>
        </template>
        </el-table-column>
      <el-table-column label="创建日期" prop="createdDate" min-width="180">
        <template #default="scope">
          <span>{{ scope.row.pmsHouseBindAplly.createdDate }}</span>
        </template>
        </el-table-column>
      <el-table-column label="操作" fixed="right" width="160" align="center">
        <template #default="scope">
          <!-- <el-button link type="primary" icon="Edit" @click="handleEdit(scope.row)">编辑</el-button> -->
           <template v-if="scope.row.pmsHouseBindAplly.auditStatus==1">
          <el-button v-hasPermi="['pms:vote:edit']" link type="primary" icon="Edit" size="small" @click="handleEdit(scope.row)">审核</el-button>
          </template>
          <!-- <el-button v-hasPermi="['pms:vote:remove']" icon="Delete" link type="primary" size="small" @click="handleDelete(scope.row)">删除</el-button> -->
        </template>
      </el-table-column>
    </el-table>
    <pagination
      v-show="total > 0"
      :total="total"
      v-model:page="queryParams.pageNum"
      v-model:limit="queryParams.pageSize"
      @pagination="getList"
    />
    <!-- 新增小区弹窗 -->
    <el-dialog
      v-model="drawerVisible"
      :title="isEdit ? '审核住户' : '新增小区'"
      width="800px"
      :close-on-click-modal="false"
      @close="closeDrawer"
    >
      <el-form ref="drawerFormRef" :model="drawerForm" :rules="drawerRules" label-width="120px">
        <el-row :gutter="20">
          <!-- <el-col :span="12"><el-form-item label="房屋ID" prop="houseRoomId" required><el-input v-model="drawerForm.houseRoomId" placeholder="请输入房屋ID" /></el-form-item></el-col>
          <el-col :span="12"><el-form-item label="住户ID" prop="liveUserId"><el-input v-model="drawerForm.liveUserId" placeholder="请输入住户ID" /></el-form-item></el-col>
          <el-col :span="12"><el-form-item label="身份" prop="identity"><el-input v-model="drawerForm.identity" placeholder="请输入身份" /></el-form-item></el-col>
          <el-col :span="12"><el-form-item label="手机号" prop="phone"><el-input v-model="drawerForm.phone" placeholder="请输入手机号" /></el-form-item></el-col>
          <el-col :span="12"><el-form-item label="姓名" prop="name"><el-input v-model="drawerForm.name" placeholder="请输入姓名" /></el-form-item></el-col> -->
          <el-col :span="12"><el-form-item label="审核状态" prop="auditStatus">
            <el-select v-model="drawerForm.pmsHouseBindAplly.auditStatus" placeholder="请选择审核状态">
              <el-option v-for="item in auditStatusOptions1" :key="item.value" :label="item.label" :value="item.value" />
            </el-select>
          </el-form-item></el-col>
          <!-- <el-col :span="12"><el-form-item label="操作员ID" prop="operatorId"><el-input v-model="drawerForm.operatorId" placeholder="请输入操作员ID" /></el-form-item></el-col>
          <el-col :span="12"><el-form-item label="小区ID" prop="communityId"><el-input v-model="drawerForm.communityId" placeholder="请输入小区ID" /></el-form-item></el-col>
          <el-col :span="12"><el-form-item label="审核日期" prop="auditDate"><el-input v-model="drawerForm.auditDate" placeholder="请输入审核日期" /></el-form-item></el-col>
          <el-col :span="12"><el-form-item label="创建日期" prop="createdDate"><el-input v-model="drawerForm.createdDate" placeholder="请输入创建日期" /></el-form-item></el-col>
          <el-col :span="12"><el-form-item label="图片" prop="images"><el-input v-model="drawerForm.images" placeholder="请输入图片URL" /></el-form-item></el-col> -->
        </el-row>
        <div style="text-align: right; margin-top: 16px;">
          <el-button @click="closeDrawer">关闭</el-button>
          <el-button type="primary" @click="handleDrawerSave">保存</el-button>
        </div>
      </el-form>
    </el-dialog>
  </div>
  

</template>

<script setup>
import { ref, reactive, toRefs, onMounted } from 'vue'
import dayjs from 'dayjs'
import { listPropertyBinding, addPropertyBinding, updatePropertyBinding, delPropertyBinding,checkPropertyBinding } from '@/api/house/propertyBinding'
const { proxy } = getCurrentInstance()
const loading = ref(false)
const bindingList = ref([])
const total = ref(0)
const drawerVisible = ref(false)
const drawerFormRef = ref(null)
const isEdit = ref(false)
const ids = ref([])
const multiple = ref(true)

const drawerForm = reactive({
  houseRoomId: '',
  liveUserId: '',
  identity: '',
  phone: '',
  name: '',
  auditStatus: '',
  operatorId: '',
  communityId: '',
  auditDate: '',
  createdDate: '',
  images: ''
})
const auditStatusOptions = ref([
  { label: '待审核', value: '1' },
  { label: '审核通过', value: '2' },
  { label: '审核不通过', value: '3' }
])
const auditStatusOptions1 = ref([
 
  { label: '审核通过', value: '2' },
  { label: '审核不通过', value: '3' }
])
const drawerRules = {
  houseRoomId: [{ required: true, message: '请输入房屋ID', trigger: 'blur' }],
  liveUserId: [{ required: true, message: '请输入住户ID', trigger: 'blur' }],
  identity: [{ required: true, message: '请选择身份', trigger: 'change' }],
  phone: [{ required: true, message: '请输入手机号', trigger: 'blur' }],
  name: [{ required: true, message: '请输入姓名', trigger: 'blur' }],
  communityId: [{ required: true, message: '请输入小区ID', trigger: 'blur' }]
}

const data = reactive({
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    houseRoomId: '',
    liveUserId: '',
    identity: '',
    phone: '',
    name: '',
    auditStatus: '',
    operatorId: '',
    communityId: '',
    auditDate: '',
    createdDate: ''
  }
})
const { queryParams } = toRefs(data)

onMounted(() => {
  getList()
})
function getList() {
  loading.value = true
  // 处理日期参数
  const params = { ...queryParams.value }
  // 处理审核日期
  if (Array.isArray(params.auditDate) && params.auditDate.length === 2) {
    params.startAuditDate = dayjs(params.auditDate[0]).format('YYYY-MM-DD HH:mm:ss')
    params.endAuditDate = dayjs(params.auditDate[1]).format('YYYY-MM-DD HH:mm:ss')
    delete params.auditDate
  }
  // 处理创建日期
  console.log('原始创建日期参数:', params.createdDate)
  if (Array.isArray(params.createdDate) && params.createdDate.length === 2) {
    params.startCreateDate = dayjs(params.createdDate[0]).format('YYYY-MM-DD HH:mm:ss')
    params.endCreateDate = dayjs(params.createdDate[1]).format('YYYY-MM-DD HH:mm:ss')
    delete params.createdDate
    console.log('转换后的创建日期参数:', params)
  } else {
    console.log('创建日期参数无效或为空')
  }
  listPropertyBinding(params).then(res => {

    
   
   let rows= res?.rows.map(e=>{
      if(e.pmsHouseBindAplly.images){
        e.pmsHouseBindAplly.images= e.pmsHouseBindAplly.images.split(",")
      }
      e.currentImageIndex = 0 // 初始化图片索引为0
      return e
    })
   
    console.log("rows",rows)
    bindingList.value = rows
    total.value = res?.total || 0
    loading.value = false
  }).catch(() => {
    loading.value = false
  })
}

function handleQuery() {
  queryParams.value.pageNum = 1
  getList()
}

function resetQuery() {
  Object.keys(queryParams.value).forEach(key => {
    queryParams.value[key] = ''
  })
  handleQuery()
}

function handleEdit(row) {
  isEdit.value = true
  drawerVisible.value = true
  row.pmsHouseBindAplly.auditStatus = row.pmsHouseBindAplly.auditStatus.toString()
  let from=JSON.parse(JSON.stringify(row))
  from.pmsHouseBindAplly.auditStatus="2"
  Object.assign(drawerForm, from)
}

function closeDrawer() {
  drawerVisible.value = false
  isEdit.value = false
  Object.assign(drawerForm, {
    houseRoomId: '',
    liveUserId: '',
    identity: '',
    phone: '',
    name: '',
    auditStatus: '',
    operatorId: '',
    communityId: '',
    auditDate: '',
    createdDate: '',
    images: ''
  })
}

function handleDrawerSave() {
  drawerFormRef.value.validate(valid => {
    if (valid) {
      const payload = { ...drawerForm.pmsHouseBindAplly }
      payload.images=payload.images.join(",")
      const req = isEdit.value ? checkPropertyBinding(payload) : addPropertyBinding(payload)
      req.then(() => {
        window.$message?.success?.('保存成功') || this?.$message?.success('保存成功')
        closeDrawer()
        getList()
      })
    }
  })
}

function handleDelete(row) {
  const delIds = row ? [row.pmsHouseBindAplly.applyId] : ids.value
  if (!delIds.length) return
  
  
  proxy.$modal.confirm('是否确认删除所选数据项?').then(function () {
    return Promise.all(delIds.map(id => delPropertyBinding(id)))
  }).then(() => {
    getList()
    proxy.$modal.msgSuccess('删除成功')
  }).catch(() => {})
}

function handleSelectionChange(selection) {
  ids.value = selection.map(item => item.id)
  multiple.value = !selection.length
}

// 图片切换相关方法
function handleImageClick(row) {
  // 点击图片时，如果有多张图片，切换到下一张
  if (row.images && row.images.length > 1) {
    const currentIndex = row.currentImageIndex || 0
    const nextIndex = (currentIndex + 1) % row.images.length
    row.currentImageIndex = nextIndex
  }
}

function prevImage(row) {
  if (row.images && row.images.length > 1) {
    const currentIndex = row.currentImageIndex || 0
    const prevIndex = currentIndex === 0 ? row.images.length - 1 : currentIndex - 1
    row.currentImageIndex = prevIndex
  }
}

function nextImage(row) {
  if (row.images && row.images.length > 1) {
    const currentIndex = row.currentImageIndex || 0
    const nextIndex = (currentIndex + 1) % row.images.length
    row.currentImageIndex = nextIndex
  }
}
</script>
  <style scoped>
  /* 提高图片预览弹窗的层级 */
  :deep(.el-image-viewer__wrapper) {
    z-index: 9999 !important;
  }
  
  :deep(.el-image-viewer__mask) {
    z-index: 9998 !important;
  }
  
  :deep(.el-image-viewer__btn) {
    z-index: 10000 !important;
  }
  
  :deep(.el-image-viewer__img) {
    z-index: 9999 !important;
  }
  </style>
